//优惠券类型 1 无门槛 2 满减
var curCouponType = "";

//发放标识筛选
var curDiffTag = "";

//适用会员筛选
var curLimitMember = "";

var $table = $("#coupon_list_table");

$(function () {
    var url = urlcore + "/api/coupon/fetchAllCouponsAdmin";
    initTable($table, url);
});

//筛选优惠券类型，刷新列表
$("#curType").change(function () {
    curCouponType = $("#curType").val();
    $table.bootstrapTable("refresh");
});

//筛选优惠券发放标识，刷新列表
$("#curDiffTag").change(function () {
    curDiffTag = $("#curDiffTag").val();
    $table.bootstrapTable("refresh");
});

//筛选优惠券适用会员，刷新列表
$("#curLimitMember").change(function () {
    curLimitMember = $("#curLimitMember").val();
    $table.bootstrapTable("refresh");
});


var columns = [
    {
        checkbox: true,
    }, {
        title: "序号",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "优惠券id",
        halign: "center",
        align: "center",
        width: "80px",
        // visible: false
    }, {
        field: "title",
        title: "优惠券名称",
        halign: "center",
        align: "center",
        width: "160px",
    }, {
        field: "displayName",
        title: "详细名称",
        halign: "center",
        align: "center",
        width: "150px",
    }, {
        field: "type",
        title: "优惠券类型",
        halign: "center",
        align: "center",
        width: "100px",
        sortable: true,
        formatter: function (value, row, index) {
            return convertCouponDic("type", value);
        }
    }, {
        field: "reachAmount",
        title: "满减条件金额",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            if (value === null)
                value = "——";
            return value;
        }
    }, {
        field: "denomination",
        title: "优惠券面值",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            if (value === null)
                value = "";
            return '<input class="list-denomination form-control" type="text" value="' + value + '">';
        }
    }, {
        field: "validityDays",
        title: "发放后有效天数",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px",
        formatter: function (value, row, index) {
            if (value === null)
                value = "——";
            return value;
        }
    }, {
        field: "expireTime",
        title: "有效期到期时间",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "100px",
        formatter: function (value, row, index) {
            console.log()
            if (value === null)
                return "——";
            return value.slice(0, -8);
        }
    }, {
        field: "limitMember",
        title: "适用会员类型",
        halign: "center",
        align: "center",
        width: "100px",
        sortable: true,
        formatter: function (value, row, index) {
            return convertCouponDic("limitMember", value);
        }
    }, {
        field: "diffTag",
        title: "发放标识",
        halign: "center",
        align: "center",
        width: "100px",
        sortable: true,
        formatter: function (value, row, index) {
            return convertCouponDic("diffTag", value);
        }
    }, {
        field: "gmtDatetime",
        title: "创建时间",
        halign: "center",
        align: "center",
        width: "150px",
    }, {
        title: "操作(普通优惠券可发放)",
        halign: "center",
        sortable: true,
        align: "center",
        width: "150px",
        formatter: function (value, row, index) {
            var optHtml = "";
            //删除优惠券
            optHtml += "\t\t\t<a class=\"btn btn-danger btn-xs\" href=\"javascript:;\" onclick=\"doDelete(" + row.id + ")\"> 删除</a>\n";
            if (row.diffTag == 1) {
                optHtml += "\t\t\t<a class=\"btn btn-default btn-xs\" href=\"javascript:;\"  onclick=\"openPublishModal(" + row.id + ",\'" + row.title + "\'"+ ")\" data-toggle=\"modal\" data-target=\"#publishModal\"> 发放</a>\n";
            }
            return optHtml;
        }
    }];

//查询参数
var queryParams = function (params) {
    console.log("params:", params);
    var param;
    param = {
        coupon: {
            type: curCouponType,
            diffTag: curDiffTag,
            limitMember: curLimitMember
        },
        page: {
            offset: params.offset,
            current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
            size: params.limit
        },
        searchText: params.search,
        // intParam: curEditingDurationId
    };

    return param;
};

//初始化表格，有已有和待选的商品两类表格 tableins:表格实例 ,
// insTag 0表示当前已添加表格 1表示待添加的表格
function initTable(tableins, url) {
    tableins.bootstrapTable({
        columns: columns,
        method: "post",
        url: url,
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        // toolbar: '#toolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 8,//每页大小
        pageList: [8, 16, 32, 48],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//搜索,未设置分页方式为"server"时只是客户端搜索
        // searchText:"",//初始搜索文本
    });
}

//刪除
function doDelete(id) {
    confirm("删除该优惠券会一起删除用户端该优惠券，确认删除吗？", function (callback) {
        if (callback) {
            delCoupon();
        }
    });

    function delCoupon() {
        $.ajax({
            type: "GET",
            url: urlcore + "/api/coupon/delCoupon?id=" + id,
            dataType: "json",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: {},
            success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
                if (data.success == true) {
                    $table.bootstrapTable("refresh");
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                alert("删除失败");
            }
        });
    }

}


//打开发布模态框，填充消息数据
function openPublishModal(row_id, title) {
    //要先设置bootstrap-table中的uniqueId: "id",得到该行原始数据
    // var row = $table.bootstrapTable('getRowByUniqueId', row_id);
    $("#publishModal").attr("data-id", row_id);
    $("#modalTitle").text(title);
    // $("#modalContent").text(row.content);
}

//发放优惠券
function publish() {
    //id
    var couponId = $("#publishModal").attr("data-id");
    var userId = $("#modalUserId").val();
    if(userId==""){
        alert("用户id不能为空");
        return;
    }
    /*    var expireTime = $("#publishModal").attr("expireTime");
        if (quId == undefined || quId == "") {
            return;
            window.location.reload();
        }
        var sex = $("input[name='sexRadio']:checked").val();
        var memberType = $("#modalMemberType").val();
        var minAge = $("#modalMinAge").val();
        var maxAge = $("#modalMaxAge").val();

        if (minAge != "" && maxAge != "") {
            minAge = parseInt(minAge);
            maxAge = parseInt(maxAge);
            if (minAge >= maxAge) {
                alert("筛选最大年龄必须不小于最小年龄");
                return;
            }
        }

        var muser = new Object();
        if (sex != "") {
            muser.sex = sex;
        }
        if (memberType != "") {
            muser.memberType = memberType;
        }
        var postData = {
            "minAge": minAge,
            "maxAge": maxAge,
            "muser": muser
        };*/
    var postData = {
        couponId: couponId,
        muserId: userId,
    }
    $.ajax({
        type: "POST",
        url: urlcore + "/api/couponUser/releaseUserCouponAdmin",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(postData),
        success: function (data) {
            console.log("cbdata", data);
            if(data.success){
                alert("发放成功");
                $table.bootstrapTable("refresh");
            }
        },
        error: function () {
            console.log("error");
        }
    });
}


/**
 * 转化优惠券数据字典
 * @param q 关键词
 * @param value 字典数值
 * @returns {string} 字典值
 */
function convertCouponDic(q, value) {
    var result = "";
    switch (q) {
        //优惠券类型
        case "type":
            if (value == 1) {
                result = "无门槛抵扣";
            }
            if (value == 2) {
                result = "满减";
            }
            break;
        //适用会员类型
        case "limitMember":
            if (value == 1) {
                result = "全部会员可用";
            }
            if (value == 2) {
                result = "仅限彩虹会员";
            }
            break;
        //优惠券发放标识
        case "diffTag":
            if (value == 1) {
                result = "普通优惠券";
            }
            if (value == 2) {
                result = "注册自动发放";
            }
            if (value == 3) {
                result = "分享邀请下载";
            }
            if (value == 4) {
                result = "分享到朋友圈";
            }
            break;
    }
    return result;
}